<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{
    protected $relationSearch = true;
    protected $searchFields = 'bind_mac,card_no';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->assignconfig("statusList", $this->model->getStatusList());
        $this->view->assign("cardTypeList", $this->model->getCardTypeListList());
        $this->assignconfig("cardTypeList", $this->model->getCardTypeListList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $add_num = $params['add_num'];
            $list = [];
            $cardNoList = $this->genCardNo($add_num);
            foreach ($cardNoList as $key => $cardNo) {
                $user['card_no'] = $cardNo;
                $user['card_type'] = $params['card_type'];
                $user['card_value'] = $params['card_value'];
                $user['status'] = $params['status'];
                $user['remark'] = $params['remark'];

                $user['group_id'] = 1;
                $user['jointime'] = date('Y-m-d H:i:s');
                $user['joinip'] = $this->request->ip();

                $list[] = $user;
            }
            $result = $this->model->allowField(true)->saveAll($list);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * @param $num string 要生成的卡密数量
     * @return array 卡密
     */
    private function genCardNo($num = 1)
    {
        // 定义卡密的长度
        $length = 16;
        // 定义允许的字符集
        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $charactersLength = strlen($characters);
        $uniqueCodes = [];

        // 生成指定数量的卡密
        for ($i = 0; $i < $num; $i++) {
            $code = '';
            for ($j = 0; $j < $length; $j++) {
                $code .= $characters[rand(0, $charactersLength - 1)];
            }
            // 检查卡密是否重复
            while (in_array($code, $uniqueCodes)) {
                $code = '';
                for ($j = 0; $j < $length; $j++) {
                    $code .= $characters[rand(0, $charactersLength - 1)];
                }
            }
            $uniqueCodes[] = $code;
        }
        // 判断生成的卡密是否和数据库的相同
        $cardNoList = $this->model->where('card_no', 'in', $uniqueCodes)->select();

        // 如果在数据库存在就再生成，直至没有重复为止
        while (!empty($cardNoList)) {
            $existingCodes = array_column((array)$cardNoList, 'card_no');
            $newCodes = [];
            foreach ($existingCodes as $existingCode) {
                $newCode = '';
                do {
                    $newCode = '';
                    for ($j = 0; $j < $length; $j++) {
                        $newCode .= $characters[rand(0, $charactersLength - 1)];
                    }
                } while (in_array($newCode, $uniqueCodes));
                $newCodes[] = $newCode;
            }

            // 替换已存在的卡密
            foreach ($existingCodes as $index => $existingCode) {
                $key = array_search($existingCode, $uniqueCodes);
                if ($key !== false) {
                    $uniqueCodes[$key] = $newCodes[$index];
                }
            }

            // 再次检查新生成的卡密是否和数据库的相同
            $cardNoList = $this->model->where('card_no', 'in', $uniqueCodes)->select();
        }

        return $uniqueCodes;
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if (!$params['start_time']) {
                unset($params['start_time']);
            }
            if (!$params['end_time']) {
                unset($params['end_time']);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        // 如果禁用用户，踢号
        if ($params['status'] == 0) {
            Auth::instance()->kick($ids);
            $this->success();
        }
        // 判断今天是否不在 $params['start_time'] 和 $params['end_time'] 之间, 不在则，踢号
        if (isset($params['start_time']) && isset($params['end_time'])) {
            $today = date('Y-m-d');
            if ($today < $params['start_time'] || $today > $params['end_time']) {
                Auth::instance()->kick($ids);
            }
        }
        $this->success();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }
}
